﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace _3dtextxna
{
    public static class Texture2DHelper
    {
        private static GraphicsDevice _graphicsDevice;
        private static SpriteBatch _spritbatch;

        public static void Initialize(GraphicsDevice graphicsDevice)
        {
            _graphicsDevice = graphicsDevice;
            _spritbatch = new SpriteBatch(graphicsDevice);
        }

        public static Texture2D ApplyEffect(this Texture2D texture, Effect effect)
        {
            RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, texture.Width, texture.Height);
            _graphicsDevice.SetRenderTarget(renderTarget);

            _graphicsDevice.Clear(Color.Transparent);

            foreach(EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                _spritbatch.Begin();
                _spritbatch.Draw(texture, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, Vector2.One, SpriteEffects.None, 1f);
                _spritbatch.End();  
            }

            _graphicsDevice.SetRenderTarget(null);

            return renderTarget;
        }

        public static Texture2D JoinTextures(this Texture2D texture1, Texture2D texture2, Vector2  texture2Position)
        {
            RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, texture1.Width, texture1.Height);
            _graphicsDevice.SetRenderTarget(renderTarget);

            _graphicsDevice.Clear(Color.Transparent);


            _spritbatch.Begin();
            _spritbatch.Draw(texture1, Vector2.Zero,Color.White);
            _spritbatch.Draw(texture1, texture2Position, Color.White);
            _spritbatch.End();

            _graphicsDevice.SetRenderTarget(null);

            return renderTarget;
        }

        //subtract textures

        public static Texture2D ResizeTexture(this Texture2D texture, Vector2 size)
        {
            RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, (int) size.X, (int) size.Y);
            _graphicsDevice.SetRenderTarget(renderTarget);

            _graphicsDevice.Clear(Color.Transparent);

            _spritbatch.Begin();
            _spritbatch.Draw(texture, Vector2.Zero, Color.White);
            _spritbatch.End();

            _graphicsDevice.SetRenderTarget(null);

            return renderTarget;
        }
    }
}
